package com.xw.Service.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.mail.Message;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.xw.Beans.MailBox;
import com.xw.Beans.SaveMail;
import com.xw.Beans.SaveMailAttachment;
import com.xw.Beans.SendingMail;
import com.xw.Cache.MailCache;
import com.xw.Dao.MailAttachmentDao;
import com.xw.Dao.MailBoxDao;
import com.xw.Dao.MailDao;
import com.xw.Mail.utils.MailSendUtil;
import com.xw.Model.Page;
import com.xw.Service.MailService;

@Transactional(rollbackFor = Exception.class)
@Service("mailService")
public class MailServiceImpl implements MailService {
	Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
	@Autowired
	private MailDao mailDao;
	@Autowired
	private MailAttachmentDao mailAttachmentDao;
	@Autowired
	private MailBoxDao mailBoxDao;
	@Autowired
	private MailSendUtil mailSendUtil;
	
	@Value("${redis.send.mail.queue}")
	private String sendQueueKey;	//待发送的邮件队列
	@Value("${redis.notify.mail.queue}")
	private String notifyQueueKey;	//待通知坐席的邮件队列
	@Autowired
	private RedisTemplate<String, Serializable> redisTemplate;

	@Override
	public void saveMail(SaveMail mail) {
		try {
			mailDao.saveMail(mail);
		} catch (Exception e) {
			logger.error("保存邮件出现异常！",e);
		}
	}

	@Override
	public Page<SaveMail> getMailPage(Page<SaveMail> page) {
		List<SaveMail> mails = mailDao.getMails(page);
		page.setTotal(mailDao.getTotalCount());
		page.setRecords(mails);
		return page;
	}

	@Override
	public SaveMail getMailById(String mid) {
		SaveMail mail = mailDao.getMailById(mid);
		return mail;
	}

	@Override
	public boolean sendMail(String whichMailBox, SendingMail mail) {
		MailBox mailBox = mailBoxDao.getMailBoxByName(whichMailBox);
		if (mailBox == null) {
			return false;
		}
		if (StringUtils.isNotEmpty(mail.getReplyMailId())) {
			SaveMail replyMail = mailDao.getMailById(mail.getReplyMailId());
			if (null!=replyMail) {
				Map<String,String> header = new HashMap<>();
				header.put("References", replyMail.getReferences()+replyMail.getMessageId());
				header.put("In-Reply-To",  replyMail.getMessageId());
				mail.setMailHeader(header);
			}
		}
		mailSendUtil.toSendMailAsync(mail, mailBox);
		return true;
	}

	@Override
	public void pushToMailSenderQueue(SendingMail mail) {
		ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
		opsForList.leftPush(sendQueueKey, mail);
	}

	@Override
	public void saveAttachments(List<SaveMailAttachment> mailAttachmentsList) {
		for (SaveMailAttachment mat : mailAttachmentsList) {
			mailAttachmentDao.saveAttachment(mat);
		}
	}

	@Override
	public int getTotalCount() {
		return mailDao.getTotalCount();
	}

	@Override
	public void offerNotifyMailQueue(SaveMail mail) {
		ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
		opsForList.leftPush(notifyQueueKey, mail);
	}

	@Override
	public void offerNewMailQueue(Message message) {
		MailCache.getNewMailQueue().offer(message);
	}

	@Override
	public Message pollNewMailQueue() {
		return MailCache.getNewMailQueue().poll();
	}

	@Override
	public String getAttachmentId() {
		return mailAttachmentDao.getAttachmentId();
	}

	@Override
	public void updateMailCallStatus(String mailId, int status) {
		mailDao.updateMailCallStatus(mailId, status);
	}

	@Override
	public List<SaveMail> getSomeUnAccessMails(int num) {
		
		//TODO 判断是否超过最大等待时长！
		
		
		
		return mailDao.getSomeUnAccessMails(num);
	}

}
